

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Han Qiu">
  <meta name="keywords" content="">
  
    <meta name="description" content="一、入门介绍1、什么是模块&#x2F;模块化 将一个复杂的程序依据一定的规则（规范）封装成几个块（文件），并进行组合在一起 块的内部数据&#x2F;实现是私有的，只是向外部暴露一些接口（方法）与其他外部模块通信  2、为什么要模块化 降低复杂度 提高解耦性（降低耦合度） 部署方便（功能点明确）  3、模块化的好处 避免命名冲突（减少命名空间污染） 更好的分离，按需加载 更高复用性 高可维护性  4、页面引入加载scr">
<meta property="og:type" content="article">
<meta property="og:title" content="js模块化规范">
<meta property="og:url" content="http://example.com/2022/01/06/js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83/index.html">
<meta property="og:site_name" content="寒秋の博客">
<meta property="og:description" content="一、入门介绍1、什么是模块&#x2F;模块化 将一个复杂的程序依据一定的规则（规范）封装成几个块（文件），并进行组合在一起 块的内部数据&#x2F;实现是私有的，只是向外部暴露一些接口（方法）与其他外部模块通信  2、为什么要模块化 降低复杂度 提高解耦性（降低耦合度） 部署方便（功能点明确）  3、模块化的好处 避免命名冲突（减少命名空间污染） 更好的分离，按需加载 更高复用性 高可维护性  4、页面引入加载scr">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/huqian025/my-images/raw/master/js/js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83/CMD.png">
<meta property="og:image" content="https://gitee.com/huqian025/my-images/raw/master/js/js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83/ES6%E4%BD%BF%E7%94%A8%E9%BB%98%E8%AE%A4%E5%AF%BC%E5%87%BA%E6%A8%A1%E5%9D%97.png">
<meta property="article:published_time" content="2022-01-06T03:31:17.000Z">
<meta property="article:modified_time" content="2022-01-06T03:33:41.948Z">
<meta property="article:author" content="Han Qiu">
<meta property="article:tag" content="js">
<meta property="article:tag" content="模块化">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/huqian025/my-images/raw/master/js/js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83/CMD.png">
  
  
  <title>js模块化规范 - 寒秋の博客</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>blogs</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="js模块化规范">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-01-06 11:31" pubdate>
        2022年1月6日 中午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.2k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      44 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">js模块化规范</h1>
            
            <div class="markdown-body">
              <h3 id="一、入门介绍"><a href="#一、入门介绍" class="headerlink" title="一、入门介绍"></a>一、入门介绍</h3><h4 id="1、什么是模块-模块化"><a href="#1、什么是模块-模块化" class="headerlink" title="1、什么是模块/模块化"></a>1、什么是模块/模块化</h4><ul>
<li>将一个复杂的程序依据一定的规则（规范）封装成几个块（文件），并进行组合在一起</li>
<li>块的内部数据/实现是私有的，只是向外部暴露一些接口（方法）与其他外部模块通信</li>
</ul>
<h4 id="2、为什么要模块化"><a href="#2、为什么要模块化" class="headerlink" title="2、为什么要模块化"></a>2、为什么要模块化</h4><ul>
<li>降低复杂度</li>
<li>提高解耦性（降低耦合度）</li>
<li>部署方便（功能点明确）</li>
</ul>
<h4 id="3、模块化的好处"><a href="#3、模块化的好处" class="headerlink" title="3、模块化的好处"></a>3、模块化的好处</h4><ul>
<li>避免命名冲突（减少命名空间污染）</li>
<li>更好的分离，按需加载</li>
<li>更高复用性</li>
<li>高可维护性</li>
</ul>
<h4 id="4、页面引入加载script问题"><a href="#4、页面引入加载script问题" class="headerlink" title="4、页面引入加载script问题"></a>4、页面引入加载script问题</h4><ul>
<li>请求过多</li>
<li>依赖模糊</li>
<li>难以维护</li>
</ul>
<h3 id="二、模块化规范"><a href="#二、模块化规范" class="headerlink" title="二、模块化规范"></a>二、模块化规范</h3><h4 id="0、不使用任何规范"><a href="#0、不使用任何规范" class="headerlink" title="0、不使用任何规范"></a>0、不使用任何规范</h4><figure class="highlight javascript"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></div></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// module1.js</span><br><span class="hljs-comment">// 定义一个没有任何依赖的模块</span><br>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-built_in">window</span></span>) </span>&#123;<br>  <span class="hljs-keyword">let</span> name = <span class="hljs-string">&#x27;module1&#x27;</span><br>  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> name<br>  &#125;<br>  <span class="hljs-built_in">window</span>.module1 = &#123;getName&#125;<br>&#125;)(<span class="hljs-built_in">window</span>)<br><br><span class="hljs-comment">// module2.js</span><br><span class="hljs-comment">// 定义一个有依赖的模块</span><br>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-built_in">window</span>, module1</span>) </span>&#123;<br>  <span class="hljs-keyword">let</span> msg = <span class="hljs-string">&#x27;module2&#x27;</span><br>  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(msg, module1.getName())<br>  &#125;<br>  <span class="hljs-built_in">window</span>.module2 = &#123;foo&#125;<br>&#125;)(<span class="hljs-built_in">window</span>, module1)<br><br><span class="hljs-comment">// app.js</span><br>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">module2</span>) </span>&#123;<br>  module2.foo()<br>&#125;)(module2)<br><br><span class="hljs-comment">// html中引入</span><br>&lt;!-- 需要发三次请求，且依赖关系不能乱 --&gt;<br><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;./js/module1.js&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;./js/module2.js&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;./app.js&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<h4 id="1、CommonJS（掌握）"><a href="#1、CommonJS（掌握）" class="headerlink" title="1、CommonJS（掌握）"></a>1、CommonJS（掌握）</h4><h5 id="1-1、规范"><a href="#1-1、规范" class="headerlink" title="1.1、规范"></a>1.1、规范</h5><ul>
<li>说明：<ul>
<li>每个js文件都可当做一个模块</li>
<li>在服务器端：模块的加载是运行时同步加载的</li>
<li>在浏览器端：模块需要提前编译打包处理</li>
</ul>
</li>
<li>基本语法：<ul>
<li>暴露模块：<ul>
<li><code>module.exports = value</code></li>
<li><code>exports.xxx = value</code></li>
<li>暴露模块本质暴露的是exports对象</li>
</ul>
</li>
<li>引入模块：<code>require(xxx)</code><ul>
<li>第三方模块：xxx为模块名</li>
<li>自定义模块：xxx为模块文件路径</li>
</ul>
</li>
</ul>
</li>
</ul>
<h5 id="1-2、实现"><a href="#1-2、实现" class="headerlink" title="1.2、实现"></a>1.2、实现</h5><ul>
<li>服务端实现：Node. js</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// module1.js</span><br><span class="hljs-comment">// module.exports = value 暴露一个对象</span><br><span class="hljs-built_in">module</span>.exports = &#123;<br>  <span class="hljs-attr">msg</span>: <span class="hljs-string">&#x27;module1&#x27;</span>,<br>  foo () &#123;<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.msg)<br>  &#125;<br>&#125;<br><br><span class="hljs-comment">// module2.js</span><br><span class="hljs-comment">// 暴露一个函数 module.exports = function()&#123;&#125;</span><br><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;module2&#x27;</span>)<br>&#125;<br><br><span class="hljs-comment">// module3.js</span><br><span class="hljs-comment">// exports.xxx = value</span><br><span class="hljs-built_in">exports</span>.foo = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;foo() module3&#x27;</span>)<br>&#125;<br><span class="hljs-built_in">exports</span>.bar= <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;bar() module3&#x27;</span>)<br>&#125;<br><br><span class="hljs-comment">// 将其他模块汇集到主模块</span><br><span class="hljs-keyword">let</span> uniq = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;uniq&#x27;</span>) <span class="hljs-comment">// 引入第三方不用写路径，一般第三方放到最上面</span><br><span class="hljs-keyword">let</span> module1 = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./modules/module1&#x27;</span>)<br><span class="hljs-keyword">let</span> module2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./modules/module2&#x27;</span>)<br><span class="hljs-keyword">let</span> module3 = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./modules/module3&#x27;</span>)<br><br>module1.foo()<br>module2()<br>module3.foo()<br>module3.bar()<br></code></pre></td></tr></table></figure>

<ul>
<li>浏览器端实现：Browserify，也称为浏览器端的打包工具（ES6也使用到）。全局安装<code>npm install browserify -g</code>，项目中安装<code>npm install browserify --save-dev</code><ul>
<li>浏览器端与node端基本相似，区别在于浏览器端需要将主模块js文件打包，并在html文件中引入打包后的js文件</li>
<li>踩坑：使用<code>browserify js/src/app.js -o js/dist/bundle.js</code>对js主模块进行打包时，会报错<code>browserify : 无法加载文件 D:\devSoftware\nodejs\node_global\browserify.ps1，因为在此系统上禁止运行脚本</code>，解决方法：以管理员身份进入命令行，切换到项目根目录，再执行上述打包命令</li>
</ul>
</li>
</ul>
<h4 id="2、AMD（掌握）"><a href="#2、AMD（掌握）" class="headerlink" title="2、AMD（掌握）"></a>2、AMD（掌握）</h4><h5 id="2-1、规范"><a href="#2-1、规范" class="headerlink" title="2.1、规范"></a>2.1、规范</h5><ul>
<li>说明：专门用于浏览器端，模块的加载是异步的</li>
<li>基本语法：<ul>
<li>定义暴露模块<ul>
<li>定义没有依赖的模块：<code>define(function() &#123; return 模块 &#125;)</code></li>
<li>定义有依赖的模块：<code>define([&#39;module1&#39;, &#39;module2&#39;], function(m1, m2) &#123; return 模块 &#125;)</code></li>
</ul>
</li>
<li>引入使用模块（可以使用require，也可以使用requirejs）<ul>
<li><code>requirejs([&#39;module1&#39;, &#39;module2&#39;], function(m1, m2) &#123; 使用m1/m2 &#125;)</code></li>
</ul>
</li>
</ul>
</li>
</ul>
<h5 id="2-2、实现（浏览器端）"><a href="#2-2、实现（浏览器端）" class="headerlink" title="2.2、实现（浏览器端）"></a>2.2、实现（浏览器端）</h5><ul>
<li>require.js，在官网或github下载require.js，并将其导入项目（如：js/libs/require.js）</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// dataService.js</span><br><span class="hljs-comment">// 定义没有依赖的模块</span><br>define(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-keyword">let</span> name = <span class="hljs-string">&#x27;dataService.js&#x27;</span><br>  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span> (<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> name<br>  &#125;<br>  <span class="hljs-comment">// 暴露模块</span><br>  <span class="hljs-keyword">return</span> &#123;getName&#125;<br>&#125;)<br><br><span class="hljs-comment">// alerter.js</span><br><span class="hljs-comment">// 定义有依赖的模块</span><br>define([<span class="hljs-string">&#x27;dataService&#x27;</span>, <span class="hljs-string">&#x27;jquery&#x27;</span>], <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">dataService, $</span>) </span>&#123;<br>  <span class="hljs-keyword">let</span> msg = <span class="hljs-string">&#x27;alerter.js&#x27;</span><br>  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMsg</span>(<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(msg, dataService.getName())<br>  &#125;<br>  $(<span class="hljs-string">&#x27;body&#x27;</span>).css(<span class="hljs-string">&#x27;background&#x27;</span>, <span class="hljs-string">&#x27;pink&#x27;</span>)<br>  <span class="hljs-comment">// 暴露模块</span><br>  <span class="hljs-keyword">return</span> &#123;showMsg&#125;<br>&#125;)<br><br><span class="hljs-comment">// main.js</span><br>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>  requirejs.config(&#123;<br>    <span class="hljs-comment">// 基本路径，使用baseUrl出发点在根目录下，不使用从自身出发</span><br>    <span class="hljs-comment">// baseUrl: &#x27;js/&#x27;,</span><br>    <span class="hljs-comment">// 配置路径</span><br>    <span class="hljs-attr">paths</span>: &#123;<br>      <span class="hljs-comment">// 模块名: 路径，文件名后不用加.js，requirejs会自动添加.js</span><br>      <span class="hljs-attr">dataService</span>: <span class="hljs-string">&#x27;./modules/dataService&#x27;</span>,<br>      <span class="hljs-attr">alerter</span>: <span class="hljs-string">&#x27;./modules/alerter&#x27;</span>,<br>      <span class="hljs-comment">// jQuery官方在AMD规范中暴露jquery</span><br>      <span class="hljs-attr">jquery</span>: <span class="hljs-string">&#x27;./libs/jquery-3.6.0&#x27;</span><br>    &#125;<br>  &#125;)<br>  requirejs([<span class="hljs-string">&#x27;alerter&#x27;</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">alerter</span>) </span>&#123;<br>    alerter.showMsg()<br>  &#125;)<br>&#125;)()<br><br><span class="hljs-comment">// html中引入</span><br>&lt;!-- data-main为根目录下主模块路径，src为根目录下<span class="hljs-built_in">require</span>.js路径 --&gt;<br><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">data-main</span>=<span class="hljs-string">&quot;js/main.js&quot;</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;js/libs/require.js&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<h4 id="3、CMD（了解）"><a href="#3、CMD（了解）" class="headerlink" title="3、CMD（了解）"></a>3、CMD（了解）</h4><h5 id="3-1、规范"><a href="#3-1、规范" class="headerlink" title="3.1、规范"></a>3.1、规范</h5><ul>
<li>说明：专门用于浏览器端，模块的加载是异步的，模块使用时才会加载执行</li>
<li>基本语法：<ul>
<li>定义暴露模块、引入使用模块</li>
<li><img src="https://gitee.com/huqian025/my-images/raw/master/js/js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83/CMD.png" srcset="/img/loading.gif" lazyload></li>
</ul>
</li>
</ul>
<h5 id="3-2、实现（浏览器端）"><a href="#3-2、实现（浏览器端）" class="headerlink" title="3.2、实现（浏览器端）"></a>3.2、实现（浏览器端）</h5><ul>
<li>Sea.js（停止维护）</li>
</ul>
<h4 id="4、ES6（掌握）"><a href="#4、ES6（掌握）" class="headerlink" title="4、ES6（掌握）"></a>4、ES6（掌握）</h4><h5 id="4-1、规范"><a href="#4-1、规范" class="headerlink" title="4.1、规范"></a>4.1、规范</h5><ul>
<li>说明：依赖模块需要编译打包处理</li>
<li>语法：<ul>
<li>导出模块：export</li>
<li>引入模块：import</li>
</ul>
</li>
</ul>
<h5 id="4-2、实现（浏览器端）"><a href="#4-2、实现（浏览器端）" class="headerlink" title="4.2、实现（浏览器端）"></a>4.2、实现（浏览器端）</h5><ul>
<li><p>核心：</p>
<ul>
<li>使用Babel将ES6编译为ES5代码</li>
<li>使用Browserify编译打包js</li>
</ul>
</li>
<li><p>使用：</p>
<ul>
<li>安装babel-cli，babel-preset-es2015和browserify<ul>
<li>npm install babel-cli browserify -g</li>
<li>npm install babel-preset-es2015 –save-dev</li>
</ul>
</li>
<li>定义 .babelrc 文件<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs json">&#123;<br>    <span class="hljs-attr">&quot;presets&quot;</span>: [<span class="hljs-string">&quot;es2015&quot;</span>]<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>编译</p>
<ul>
<li>使用Babel将ES6编译为ES5代码（但还是包含CommonJS语法）：babel js/src -d js/build</li>
<li>使用Browserify编译js：browserify js/build/main.js -o js/dist/bundle.js</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// module1.js</span><br><span class="hljs-comment">// 常规暴露-分别暴露</span><br><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;foo() module1&#x27;</span>)<br>&#125;<br><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;bar() module1&#x27;</span>)<br>&#125;<br><span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]<br><br><span class="hljs-comment">// module2.js</span><br><span class="hljs-comment">// 常规暴露-统一暴露</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;fun() module2&#x27;</span>)<br>&#125;<br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun2</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;fun2() module2&#x27;</span>)<br>&#125;<br><span class="hljs-keyword">export</span> &#123;fun, fun2&#125;<br><br><span class="hljs-comment">// module3.js</span><br><span class="hljs-comment">// 默认暴露，可以暴露任意数据类型，暴露什么数据接收到的就是什么数据</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> &#123;<br>  <span class="hljs-attr">msg</span>: <span class="hljs-string">&#x27;默认暴露&#x27;</span>,<br>  foo () &#123;<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.msg)<br>  &#125;<br>&#125;<br><br><span class="hljs-comment">// main.js</span><br><span class="hljs-comment">// 引入模块</span><br><span class="hljs-comment">// 常规暴露必须使用解构赋值的形式引入</span><br><span class="hljs-keyword">import</span> &#123;foo, bar&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./module1&#x27;</span><br><span class="hljs-keyword">import</span> &#123; fun, fun2 &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./module2&#x27;</span><br><span class="hljs-comment">// 默认暴露直接引入</span><br><span class="hljs-keyword">import</span> module3 <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./module3&#x27;</span><br><span class="hljs-comment">// 引入第三方库类似默认暴露，以jquery为例</span><br><span class="hljs-keyword">import</span> $ <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;jquery&#x27;</span><br>$(<span class="hljs-string">&#x27;body&#x27;</span>).css(<span class="hljs-string">&#x27;background&#x27;</span>, <span class="hljs-string">&#x27;green&#x27;</span>)<br>foo()<br>bar()<br>fun()<br>fun2()<br>module3.foo()<br><br><span class="hljs-comment">// html中引入</span><br>&lt;!-- 引入通过babel和browserify打包处理后的js文件 --&gt;<br><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;./js/dist/bundle.js&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<h3 id="三、ES6引入export-default导出的模块，不使用"><a href="#三、ES6引入export-default导出的模块，不使用" class="headerlink" title="三、ES6引入export default导出的模块，不使用{}"></a>三、ES6引入export default导出的模块，不使用{}</h3><p><img src="https://gitee.com/huqian025/my-images/raw/master/js/js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83/ES6%E4%BD%BF%E7%94%A8%E9%BB%98%E8%AE%A4%E5%AF%BC%E5%87%BA%E6%A8%A1%E5%9D%97.png" srcset="/img/loading.gif" lazyload></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/js/">js</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/js/">js</a>
                    
                      <a class="hover-with-bg" href="/tags/%E6%A8%A1%E5%9D%97%E5%8C%96/">模块化</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/06/js%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">js数组中的高阶函数</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/01/06/ajax%E5%9F%BA%E7%A1%80/">
                        <span class="hidden-mobile">ajax基础</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
